//
//  CTFinanceTransformVC.m
//  digitalCurrency
//
//  Created by apple on 2019/6/12.
//  Copyright © 2019 XinHuoKeJi. All rights reserved.
//

#import "CTFinanceTransformVC.h"
#import "CTQGListVC.h"
#import "FinanceHeadView.h"
#import "HomeNetManager.h"
#import "CTFinanceTransformOutVC.h"
#import "CTFinanceTransformInVC.h"
#import "CTQGCell.h"

@interface CTFinanceTransformVC ()
@property (nonatomic,copy) NSMutableArray *contentArr;
@property (nonatomic, strong) LYEmptyView *emptyView;
@property (nonatomic, strong) FinanceHeadView *homeHeadView;
@property (nonatomic, strong) UIView *sectionHeader;

@property (nonatomic, strong) UIButton *transformIn;
@property (nonatomic, strong) UIButton *transformOut;

@property (nonatomic, assign) NSInteger page;

@end

@implementation CTFinanceTransformVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
    self.viewTitle.text = LocalizationKey(@"Financial");
    _page = 1;
    [self.view addSubview:self.tableView];
    self.tableView.rowHeight = 62;
    self.tableView.separatorColor = [UIColor clearColor];
    [self.tableView registerClass:[CTQGCell class] forCellReuseIdentifier:@"qgcell"];
    
    [self setTablewViewHeard];
    [self headRefreshWithScrollerView:self.tableView];
    [self footRefreshWithScrollerView:self.tableView];

    self.tableView.ly_emptyView = self.emptyView;
    
    [self.view addSubview:self.transformIn];
    [self.view addSubview:self.transformOut];
    
    [self setCntZero];
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    CGRect rect = self.view.bounds;
    rect.size.height -= (kTabBarHeight+60);
    self.tableView.frame = rect;
}

- (void)setCntZero {
    [[NSUserDefaults standardUserDefaults] setObject:@"0" forKey:@"financeCnt"];
    [[NSUserDefaults standardUserDefaults] setObject:@"0" forKey:@"balanceCnt"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

#pragma mark-下拉刷新数据
- (void)refreshHeaderAction {
    _page = 1;
    [self getFinanceList];
    [self getFinancingsInfo];
}

- (void)refreshFooterAction {
    _page++;
    [self getFinanceList];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    
    CGRect rect = self.view.bounds;
    rect.size.height -= (kTabBarHeight+20);
    self.tableView.frame = rect;
    
    if(![YLUserInfo isLogIn]) {
        [self showLoginViewController];
    }
    else {
        [self getFinancingsInfo];
        [self getFinanceList];
        
        NSString *fcnt = [[NSUserDefaults standardUserDefaults] objectForKey:@"financeCnt"];
        self.financingCnt = [NSString stringWithFormat:@"%f",[self.financingCnt floatValue] - [fcnt floatValue]];
        
        NSString *bcnt = [[NSUserDefaults standardUserDefaults] objectForKey:@"balanceCnt"];
        self.canusedBalance = [NSString stringWithFormat:@"%f",[self.canusedBalance floatValue] - [bcnt floatValue]];
        
        [self setCntZero];
    }
}

-(void)setTablewViewHeard {
    self.homeHeadView = [[FinanceHeadView alloc]initWithFrame:CGRectMake(0, 0, kWindowW,  123)];
    self.tableView.tableHeaderView = self.homeHeadView;
    self.tableView.tableFooterView = [UIView new];
    
    if (@available(iOS 11.0, *)){
        self.tableView.estimatedRowHeight = 0;
        self.tableView.estimatedSectionHeaderHeight = 0;
        self.tableView.estimatedSectionFooterHeight = 0;
    }
}

- (void)getFinanceList {
    __weak typeof(self)weakself = self;
    [EasyShowLodingView showLodingText:LocalizationKey(@"loading")];
    NSDictionary *dic = @{@"pageNum":@(_page),@"pageSize":@"20",@"coinId":self.unit};
    [HomeNetManager getFinancingsIncomeLogsWithInfo:dic CompleteHandle:^(id resPonseObj, int code) {
        [EasyShowLodingView hidenLoding];
        NSLog(@"resPonseObj:%@",resPonseObj);
        if (code) {
            NSInteger codeInt = [resPonseObj[@"code"] integerValue];
            if (codeInt == 0) {
                NSArray *data = resPonseObj[@"data"][@"list"];
                
                if (_page == 1) {
                    [self.contentArr removeAllObjects];
                }
                else {
                    if (data.count == 0) {
                        self.tableView.mj_footer.state = MJRefreshStateNoMoreData;
                    }
                }
                
                for (NSDictionary *sub in data) {
                    [self.contentArr addObject:sub];
                }
                self.tableView.ly_emptyView = self.emptyView;
                [self.tableView reloadData];
            }
            else if (codeInt == -1000001 ){
                [ShowLoGinVC showLoginVc:self withTipMessage:resPonseObj[MESSAGE]];
            }
            else {
                [weakself.view makeToast:resPonseObj[MESSAGE] duration:1.5 position:CSToastPositionCenter];
            }
        }
        else {
            [weakself.view makeToast:[[ChangeLanguage bundle] localizedStringForKey:@"noNetworkStatus" value:nil table:@"English"] duration:1.5 position:CSToastPositionCenter];
        }
    }];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.contentArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 62;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return self.sectionHeader;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CTQGCell *cell = [CTQGCell createTableView:tableView];
    
    NSDictionary *dic = _contentArr[indexPath.row];
    cell.createTime.text = [NSString stringWithFormat:@"%@",dic[@"date"]];
    cell.coinNumber.text = [NSString stringWithFormat:@"%@ %@",[NSString stringWithFormat:@"%@", [ToolUtil judgeStringForDecimalPlaces:[dic[@"value"] stringValue] point:4]],dic[@"tocoinName"]];
    cell.coinName.text = [NSString stringWithFormat:@"%@",dic[@"coinName"]];

    cell.bgView.frame = CGRectMake(0, 0, kWindowW, 62);
    cell.bgView.layer.cornerRadius = 0.01;
    cell.bgView.layer.shadowColor = [UIColor whiteColor].CGColor;
    
    if (indexPath.row%2!=0) {
        cell.bgView.backgroundColor = [[UIColor colorWithHEX:mainBlackColor] colorWithAlphaComponent:0.5];
    }
    else {
        cell.bgView.backgroundColor = [UIColor whiteColor];
    }
    
    return cell;
}

- (void)getFinancingsInfo {
    [HomeNetManager getFinancingsInfoWithInfo:@{@"coinId":self.unit} CompleteHandle:^(id resPonseObj, int code) {
        if (code) {
            [self.contentArr removeAllObjects];
            
            NSDictionary *data = resPonseObj[@"data"];
            
            NSString *Asset = [data[@"invest"] stringValue];
            self.homeHeadView.amountCoin.text = [NSString stringWithFormat:@"%@",[ToolUtil judgeStringForDecimalPlaces:Asset point:4]];
            
            self.financingCnt = self.homeHeadView.amountCoin.text;

            NSString *Income = [data[@"income"] stringValue];
            self.homeHeadView.canUsedCoin.text = [NSString stringWithFormat:@"%@",[ToolUtil judgeStringForDecimalPlaces:Income point:4]];
        }
        else {
            [self.view makeToast:LocalizationKey(@"noNetworkStatus") duration:1.5 position:CSToastPositionCenter];
        }
    }];
}

- (void)transformInClick {
    CTFinanceTransformInVC *vc = [[CTFinanceTransformInVC alloc] init];
    vc.balance = [ToolUtil judgeStringForDecimalPlaces:self.canusedBalance point:4];
    vc.unit    = self.unit;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)transformOutClick {
    CTFinanceTransformOutVC *vc = [[CTFinanceTransformOutVC alloc] init];
    vc.financingCnt = [ToolUtil judgeStringForDecimalPlaces:self.financingCnt point:4];
    vc.unit    = self.unit;
    [self.navigationController pushViewController:vc animated:YES];
}

- (UIView *)sectionHeader {
    if (!_sectionHeader) {
        _sectionHeader = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 60)];
        _sectionHeader.backgroundColor = [UIColor whiteColor];
        
        UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"financeSection"]];
        imgView.frame = CGRectMake(15, 23, 14, 14);
        imgView.tintColor = tMainColor;
        [_sectionHeader addSubview:imgView];
        
        UILabel *title = [[UILabel alloc] init];
        [_sectionHeader addSubview:title];
        [title mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(imgView.mas_right).offset(7);
            make.centerY.equalTo(imgView);
        }];
        title.textColor = tThreeColor;
        title.text = LocalizationKey(@"Revenue record");
        title.font = [UIFont systemFontOfSize:14];
        
        UIView *lineView = [[UIView alloc]init];
        [_sectionHeader addSubview:lineView];
        [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(0);
            make.bottom.equalTo(0);
            make.height.equalTo(0.5);
        }];
        lineView.backgroundColor = tTableViewCellLine;
    }
    
    return _sectionHeader;
}

- (LYEmptyView *)emptyView {
    if (!_emptyView) {
        _emptyView = [LYEmptyView emptyViewWithImageStr:@"emptyData" titleStr:[[ChangeLanguage bundle] localizedStringForKey:@"NoData" value:nil table:@"English"]];
        _emptyView.titleLabTextColor = tThreeColor;
        _emptyView.titleLabFont = [UIFont systemFontOfSize:19];
        _emptyView.contentViewY = SCREEN_HEIGHT/2.0-20;
    }
    return _emptyView;
}

- (UIButton *)transformIn {
    if (!_transformIn) {
        _transformIn = [UIButton buttonWithType:UIButtonTypeCustom];
        CGFloat viewH = SCREEN_HEIGHT;
        CGFloat btnW = SCREEN_WIDTH/2.0 - 36;
        _transformIn.frame = CGRectMake(18, viewH-kTopHeight-kTabBarHeight-20, btnW, 44);
        _transformIn.layer.cornerRadius = 5;
        _transformIn.titleLabel.font = [UIFont systemFontOfSize:17];
        _transformIn.backgroundColor = [UIColor colorWithHEX:maincolor];
        [_transformIn setTitle:LocalizationKey(@"Transfer-in") forState:UIControlStateNormal];
        [_transformIn addTarget:self action:@selector(transformInClick) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _transformIn;
}

- (UIButton *)transformOut {
    if (!_transformOut) {
        CGFloat viewH = SCREEN_HEIGHT;
        CGFloat btnW = SCREEN_WIDTH/2.0 - 36;
        _transformOut = [UIButton buttonWithType:UIButtonTypeCustom];
        _transformOut.frame = CGRectMake(btnW + 18*3, viewH-kTopHeight-kTabBarHeight-20, btnW, 44);
        _transformOut.layer.cornerRadius = 5;
        _transformOut.titleLabel.font = [UIFont systemFontOfSize:17];
        _transformOut.backgroundColor = [UIColor colorWithHEX:maincolor];
        [_transformOut setTitle:LocalizationKey(@"Transfer-out") forState:UIControlStateNormal];
        [_transformOut addTarget:self action:@selector(transformOutClick) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _transformOut;
}

- (NSMutableArray *)contentArr
{
    if (!_contentArr) {
        _contentArr = [NSMutableArray array];
    }
    return _contentArr;
}

@end
